package com.jintian.smart.platform.system.service;

import com.jintian.smart.base.api.system.entity.HelpEntity;
import com.jintian.smart.base.api.system.form.HelpViewRecordQueryForm;
import com.jintian.smart.base.api.system.view.HelpDetailVO;
import com.jintian.smart.base.api.system.view.HelpVO;
import com.jintian.smart.base.api.system.view.HelpViewRecordVO;
import com.jintian.smart.kernel.common.util.SmartBeanUtil;
import com.jintian.smart.kernel.core.domain.RequestUser;
import com.jintian.smart.kernel.core.domain.ResponseDTO;
import com.jintian.smart.platform.system.mapper.HelpMapper;
import jakarta.annotation.Resource;
import org.beetl.sql.core.page.PageResult;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户查看  帮助文档
 */
@Service
public class HelpUserService {
    @Resource
    private HelpMapper helpMapper;

    /**
     * 查询全部 帮助文档
     *
     * @return
     */
    public ResponseDTO<List<HelpVO>> queryAllHelpDocList() {
        return ResponseDTO.ok(helpMapper.queryAllHelpDocList());
    }


    /**
     * 查询我的 待查看的 帮助文档清单
     *
     * @return
     */
    public ResponseDTO<HelpDetailVO> view(RequestUser requestUser, Long helpDocId) {
        HelpEntity helpEntity = helpMapper.single(helpDocId);
        if (helpEntity == null) {
            return ResponseDTO.userErrorParam("帮助文档不存在");
        }

        HelpDetailVO helpDetailVO = SmartBeanUtil.copy(helpEntity, HelpDetailVO.class);
        long viewCount = helpMapper.viewRecordCount(helpDocId, requestUser.getUserId());
        if (viewCount == 0) {
            helpMapper.insertViewRecord(helpDocId, requestUser.getUserId(), requestUser.getUserName(), requestUser.getIp(), requestUser.getUserAgent(), 1);
            helpMapper.updateViewCount(helpDocId, 1, 1);
            helpDetailVO.setPageViewCount(helpDetailVO.getPageViewCount() + 1);
            helpDetailVO.setUserViewCount(helpDetailVO.getUserViewCount() + 1);
        } else {
            helpMapper.updateViewRecord(helpDocId, requestUser.getUserId(), requestUser.getIp(), requestUser.getUserAgent());
            helpMapper.updateViewCount(helpDocId, 0, 1);
            helpDetailVO.setPageViewCount(helpDetailVO.getPageViewCount() + 1);
        }

        return ResponseDTO.ok(helpDetailVO);
    }


    /**
     * 分页查询  查看记录
     *
     * @param helpViewRecordQueryForm
     * @return
     */
    public PageResult<HelpViewRecordVO> queryViewRecord(HelpViewRecordQueryForm helpViewRecordQueryForm) {
        PageResult<HelpViewRecordVO> noticeViewRecordVOSPage = helpMapper.queryViewRecordPage(helpViewRecordQueryForm);
        return noticeViewRecordVOSPage;
    }
}
